/**
 * Created by kangdaye on 16/6/5.
 */
app.controller('aEGoodsCtr',["$scope","$rootScope","$stateParams","ngDialog","Upload","goodsListCache","goodsListService", function($scope,$rootScope,$stateParams,ngDialog,Upload,goodsListCache,goodsListService) {
    var model = $stateParams.model;
    var editor = KindEditor.create('#editor',{
        filePostName : 'file',
        minHeight : 200,
        uploadJson: servicePath + 'goods/upload_image'
    });


    $scope.getData = {};
    $scope.freightList = {};
    $scope.viewData = {
        categoryData : goodsListCache.category,
        promotionTypeData : goodsListCache.promotionType,
        upLoadImg : []
    };

    $scope.upload = function (file,index) {
        Upload.upload({
            url: servicePath + 'goods/upload_image',
            data: {file: file}
        }).then(function (resp) {
            if(index >= 0){
                $scope.viewData.upLoadImg.splice(index,1,resp.data.data);
                return
            }
            $scope.viewData.upLoadImg.push(resp.data.data);
        });
    };

    $scope.unimg = function(index){
        $scope.viewData.upLoadImg.splice(index,1);
    };

    $scope.submit = function(){
        $scope.getData.descr = editor.html();
        $scope.getData.images = $scope.viewData.upLoadImg.toString();
        if(model === 'add'){
            goodsListService.add($scope.getData,function(){
                location.href = $rootScope.prefix + 'goods/goodsList/list.html';
            });
            return;
        }
        goodsListService.update($scope.getData,function(){
            location.href = $rootScope.prefix + 'goods/goodsList/list.html';
        });
    };

    goodsListService.freightList(function(data){
        $scope.freightList = data.data;
    });

    if(model !== 'add'){
        goodsListService.details({
            id : model
        },function(data){
            $scope.getData = data.data;
            $scope.getData.discount = data.data.promotionParams.discount;
            $scope.getData.promotionType = data.data.promotionParams.type;
            $scope.getData.presentPrice = data.data.promotionParams.presentPrice;
            $scope.getData.weight = data.data.productParams.weight;
            $scope.viewData.upLoadImg = data.data.images;
            $scope.getData.price = $scope.getData.originPrice;
            editor.html($scope.getData.descr)
        });
    }
}]);
